var source = null; //新绘制图层的source
var vector = null; //新绘制图层的layer
var draw = null;

var area = 0; //面积亩
var perimeter = 0; //周长米
var coordinates = []; //当前多边形的点数据
var onCoordinatesChanged = null //监听面积周长返回
var features_0 = null; //记录的第一个点数据
var backCursor = 0; //进行回退操作的游标
var features = []; //绘制地块或修改地块，记录每一步操作的地块数据，方便进行回退操作

//***绘制地块时的变量*****
var firstPoint = null; //绘制地块第一个点
var addPoint = []; //记录绘制地块时的点
var operations = []; //记录绘制地块时的每一步操作
var isDraw = false; //是否正在绘制
var $map_array = null;
//***绘制地块时的变量*****
var bj = 0; //选择的点是否是多边形的顶点：0代表否，1代表是

//***********获取当前系统*************
var anorios = 0;
//***0代表安卓,1代表ios*****
var a = window.localStorage.getItem("OSTYPE");
if (a == undefined) {
	anorios = 2;
} else {
	anorios = Number(a);
}
//***********获取当前系统*************

var GeometryDraw = function GeometryDraw($map) {

	//********绘制多边形的样式***********
	var styles = [
		new ol.style.Style({
			fill: new ol.style.Fill({
				color: 'rgba(255, 255, 255, 0.2)'
			}),
			stroke: new ol.style.Stroke({
				color: '#ffcc33',
				width: 1
			}),
			image: new ol.style.Circle({
				radius: 8,
				fill: new ol.style.Fill({
					color: '#ffcc33'
				})
			}),
			geometry: function(feature) {
				// return the coordinates of the first ring of the polygon
				if (feature.getGeometry() instanceof ol.geom.Polygon) {
					var coordinates = feature.getGeometry().getCoordinates()[0];
					if (coordinates != undefined) {
						var last = coordinates.pop();
						//coordinates.pop();
						coordinates.push(last);
						return new ol.geom.Polygon([coordinates]);
					}
				}

			}
		}),
		new ol.style.Style({
			image: new ol.style.Circle({
				radius: 8,
				fill: new ol.style.Fill({
					color: 'rgba(255, 255, 255, 0.9)'
				}),
				stroke: new ol.style.Stroke({
					color: '#ffffff',
					width: 2
				})
			}),
			geometry: function(feature) {
				// return the coordinates of the first ring of the polygon
				if (feature.getGeometry() instanceof ol.geom.Polygon) {
					var coordinates = feature.getGeometry().getCoordinates()[0];
					if (coordinates != undefined) {
						var last = coordinates.pop();
						//coordinates.pop();
						if (coordinates.length == 0) {
							if (isfirst) {
								coordinates.push(last);
							}
							isfirst = false;
						}
						return new ol.geom.MultiPoint(coordinates);
					} else {
						isfirst = true;
					}
				}
			}
		}),
		new ol.style.Style({
			image: new ol.style.Circle({
				radius: 2,
				fill: new ol.style.Fill({
					color: 'rgba(255, 255, 255, 0.1)'
				}),
				stroke: new ol.style.Stroke({
					color: '#ffffff',
					width: 2

				})
			}),
			geometry: function(feature) {
				// return the coordinates of the first ring of the polygon
				if (feature.getGeometry() instanceof ol.geom.Polygon) {
					var coordinates = feature.getGeometry().getCoordinates()[0];
					if (coordinates != undefined) {
						var coordinatesCenter = [];
						var j = coordinates.length - 1;
						for (var i = 0; i < coordinates.length; i++) {
							coordinatesCenter.push([(coordinates[j][0] + coordinates[i][0]) / 2, (
									coordinates[j][1] + coordinates[
										i][1]) /
								2
							])
							j = i;
						}
						return new ol.geom.MultiPoint(coordinatesCenter);
					}
				}

			}
		})

	];
	//********绘制多边形的样式***********
	//***********自定义绘制的方法*******************
	function drawPolygon() {
		if (vector != null) {
			$map.removeLayer(vector);
		}
		vector = null;
		var drawfeatures = [];
		var lng = addPoint.length;
		if (lng == 0)
			return;
		if (lng == 1) {
			//第一个点只需要画点
			var featurePoint = new ol.Feature(
				new ol.geom.Point(
					addPoint[lng - 1]
				)
			);

			featurePoint.setStyle(new ol.style.Style({
				image: new ol.style.Circle({
					radius: 8,
					fill: new ol.style.Fill({
						color: 'rgba(255, 255, 255, 0.9)'
					}),
					stroke: new ol.style.Stroke({
						color: '#ffffff',
						width: 2
					})
				})
			}));
			firstPoint = featurePoint;
			drawfeatures.push(featurePoint);
		} else {
			//其它点画线、点及中点
			var featurePoint = null;
			for (var i = 0, cnt = addPoint.length - 1; i < cnt; i++) {
				var currentPoint = addPoint[i];
				var nextPoint = addPoint[i + 1];
				featurePoint = new ol.Feature(
					new ol.geom.Point(
						currentPoint
					)
				);
				featurePoint.setStyle(new ol.style.Style({
					image: new ol.style.Circle({
						radius: 8,
						fill: new ol.style.Fill({
							color: 'rgba(255, 255, 255, 0.9)'
						}),
						stroke: new ol.style.Stroke({
							color: '#ffffff',
							width: 2
						})
					})
				}));
				var featureCenter = new ol.Feature(
					new ol.geom.Point(
						[(currentPoint[0] + nextPoint[0]) / 2, (currentPoint[1] + nextPoint[1]) / 2]
					)
				);
				featureCenter.setStyle(new ol.style.Style({
					image: new ol.style.Circle({
						radius: 2,
						fill: new ol.style.Fill({
							color: 'rgba(255, 255, 255, 0.1)'
						}),
						stroke: new ol.style.Stroke({
							color: '#ffffff',
							width: 2

						})
					})
				}));
				var featureLine = new ol.Feature(
					new ol.geom.LineString(
						[currentPoint, nextPoint]
					)
				);
				featureLine.setStyle(new ol.style.Style({
					fill: new ol.style.Fill({ //填充样式
						color: 'rgba(255, 255, 255, 0.2)'
					}),
					stroke: new ol.style.Stroke({ //线样式
						color: '#ffcc33',
						width: 1
					})
				}));
				drawfeatures.push(featurePoint);
				drawfeatures.push(featureCenter);
				drawfeatures.push(featureLine);
			}

			featurePoint = new ol.Feature(
				new ol.geom.Point(
					addPoint[lng - 1]
				)
			);
			featurePoint.setStyle(new ol.style.Style({
				image: new ol.style.Circle({
					radius: 8,
					fill: new ol.style.Fill({
						color: 'rgba(255, 255, 255, 0.1)'
					}),
					stroke: new ol.style.Stroke({
						color: '#ffffff',
						width: 2
					})
				})
			}));
			drawfeatures.push(featurePoint);
		}

		//清空矢量数据源
		source = null;
		source = new ol.source.Vector({
			features: drawfeatures
		});
		vector = new ol.layer.Vector({
			source: source
		});
		//将绘制层添加到地图容器中
		$map.addLayer(vector);
		var _tmp = []
		_tmp = _tmp.concat(addPoint);
		_tmp.push(_tmp[0]);
		var geom = new ol.geom.Polygon([_tmp]);
		//计算两点间的距离(米)
		/*if(addPoint.length > 1) {
			var dist = ol.sphere.getDistance(ol.proj.transform(addPoint[0], 'EPSG:3857', 'EPSG:4326'), ol.proj.transform(
				addPoint[(addPoint.length - 1)], 'EPSG:3857', 'EPSG:4326'));
		}*/
		//计算面积(亩)
		area = ((Math.abs(ol.sphere.getArea(geom)) * 0.0015).toFixed(2)).toString();
		console.log("面积", area);
		perimeter = ((Math.abs(ol.sphere.getLength(geom))).toFixed(2)).toString();
		console.log("周长", perimeter);

		// 返回监听面积 周长
		typeof onCoordinatesChanged === 'function' && onCoordinatesChanged({
			area: area,
			perimeter: perimeter
		});
	}
	//***********自定义绘制的方法*******************

	//**********图层绘制控件***************
	var Draw = {
		init: function() {
			if (vector != null) {
				$map.removeLayer(vector);
				vector = null;
			}
			//初始化矢量数据源对象
			source = new ol.source.Vector({});
			//实例化矢量数据图层
			vector = new ol.layer.Vector({
				//数据源
				source: source,
				//样式
				style: styles
			});
			//将矢量图层加载到map中
			$map.addLayer(vector);
			//开启绘制状态
			isDraw = true;

			//自定义绘制的方法
			drawPolygon();

			//*********本项目不要自动闭合，所以不用openlayer自带的Draw控件*******
			/*//开启动态绘制（开启交互绘制图形）
			draw = new ol.interaction.Draw({
				//数据源
				source: source,
				//绘制类型
				type: 'Polygon',
				style: styles
			})
			//将draw对象添加到map中，然后就可以进行图形绘制了
			$map.addInteraction(draw);
			//绑定开始绘制事件
			draw.on('drawstart', this.getdrawStart());
			//绑定绘制结束事件
			draw.on('drawend', this.getdrawEnd());*/

		},
		getdrawStart: function() {
			drawStart = function() {
				console.log("***开始绘制***");
			}
			return drawStart;
		},
		getdrawEnd: function() {
			drawEnd = function(evt) {
				var geom = evt.feature.getGeometry();
				if (geom.getType() == 'Circle') {
					console.log(geom.getCenter());
					console.log(geom.getRadius());
					console.log("圆形：" + geom.getCenter() + "," + geom.getRadius());
				} else {
					const points = geom.getCoordinates();
					console.log("返回坐标：" + points);

					Modify.select_feature = evt.feature; //选中要素
					Modify.init();
					Modify.setActive(true); //开启选择控件、修改控件

					//从map中移除交互绘图对象
					//如果不移除，则会在下拉列表框选项发生改变时再次进行绘制时，保留上一次的draw对象
					$map.removeInteraction(draw);

				}

				//计算面积\周长
				//openlayers 5.3.0版本计算面积
				area = ((Math.abs(ol.sphere.getArea(geom)) * 0.0015).toFixed(2)).toString(); //亩
				perimeter = ((Math.abs(ol.sphere.getLength(geom))).toFixed(2)).toString(); //米
				console.log("面积", area);
				console.log("周长", perimeter);

				console.log("***绘制结束***");
			}

			return drawEnd;
		},
		del: function() {
			$map.removeLayer(vector);
			//清空矢量数据源
			source = null;
			//设置矢量图层的数据源为空
			if (vector != null) {
				vector.setSource(source);
			}

			firstPoint = null; //绘制地块第一个点
			addPoint = []; //记录绘制地块时的点
			operations = []; //记录绘制地块时的每一步操作
			isDraw = false; //是否正在绘制

			backCursor = 0;
			features = [];

			//*********本项目不要自动闭合，所以不用openlayer自带的Draw控件*******
			/*if(draw != null) {
				//清空矢量数据源
				source = null;
				//设置矢量图层的数据源为空
				vector.setSource(source);
				Modify.setActive(false); //关闭选择控件、修改控件

				//从map中移除交互绘图对象
				//如果不移除，则会在下拉列表框选项发生改变时再次进行绘制时，保留上一次的draw对象
				$map.removeInteraction(draw);
				draw = null;
			}
			//Modify.setActive(false); //关闭选择控件、修改控件
			* */

		}

	};
	//**********图层绘制控件***************
	//**********图层选择、修改控件***************
	var Modify = {
		m_style: function() { //基本样式
			var that = this;
			var styles = [
				new ol.style.Style({
					fill: new ol.style.Fill({
						color: 'rgba(255, 255, 255, 0.2)'
					}),
					stroke: new ol.style.Stroke({
						color: '#ffcc33',
						width: 1
					}),
					image: new ol.style.Circle({
						radius: 8,
						fill: new ol.style.Fill({
							color: '#ffcc33'
						})
					}),
					geometry: function(feature) {
						// return the coordinates of the first ring of the polygon
						if (feature.getGeometry() instanceof ol.geom.Polygon) {
							var coordinates = feature.getGeometry().getCoordinates()[0];
							if (coordinates != undefined) {
								var last = coordinates.pop();
								//coordinates.pop();
								coordinates.push(last);
								return new ol.geom.Polygon([coordinates]);
							}
						}

					}
				}),
				new ol.style.Style({
					image: new ol.style.Circle({
						radius: 8,
						fill: new ol.style.Fill({
							color: 'rgba(255, 255, 255, 0.9)'
						}),
						stroke: new ol.style.Stroke({
							color: '#ffffff',
							width: 2
						})
					}),
					geometry: function(feature) {
						// return the coordinates of the first ring of the polygon
						if (feature.getGeometry() instanceof ol.geom.Polygon) {
							var coordinates = feature.getGeometry().getCoordinates()[0];
							if (coordinates != undefined) {
								var last = coordinates.pop();
								//coordinates.pop();
								if (coordinates.length == 0) {
									if (isfirst) {
										coordinates.push(last);
									}
									isfirst = false;
								}
								return new ol.geom.MultiPoint(coordinates);
							} else {
								isfirst = true;
							}
						}
					}
				}),
				new ol.style.Style({
					image: new ol.style.Circle({
						radius: 2,
						fill: new ol.style.Fill({
							color: 'rgba(255, 255, 255, 0.1)'
						}),
						stroke: new ol.style.Stroke({
							color: '#ffffff',
							width: 2

						})
					}),
					geometry: function(feature) {
						// return the coordinates of the first ring of the polygon
						if (feature.getGeometry() instanceof ol.geom.Polygon) {
							var coordinates = feature.getGeometry().getCoordinates()[0];
							if (coordinates != undefined) {
								var coordinatesCenter = [];
								var j = coordinates.length - 1;
								for (var i = 0; i < coordinates.length; i++) {
									coordinatesCenter.push([(coordinates[j][0] + coordinates[i][
											0
										]) / 2, (coordinates[j][1] + coordinates[
											i][1]) /
										2
									])
									j = i;
								}
								return new ol.geom.MultiPoint(coordinatesCenter);
							}
						}

					}
				}),
				new ol.style.Style({
					zIndex: 1000,
					image: new ol.style.Circle({
						radius: 8,
						fill: new ol.style.Fill({
							color: 'rgba(0, 153, 255, 0.9)'
						}),
						stroke: new ol.style.Stroke({
							color: '#ffffff',
							width: 2
						})
					}),
					geometry: function(feature) { //选择点的样式
						// return the coordinates of the first ring of the polygon
						if (feature.getGeometry() instanceof ol.geom.Polygon) {

							var old_point = that.cache_point;
							var coordinates = feature.getGeometry().getCoordinates()[0];
							that.cache_point = coordinates;
							if (old_point == null) { //如果没有历史缓存的多边形
								if (that.select_point != null) { //没有缓存的点
									if (that.select_point_index == null) {
										return null;
									}
									//返回缓存的点
									return new ol.geom.MultiPoint([
										that.select_point_index
									]);
								}
							} else {
								//循环比对数组
								for (var i = 0; i < old_point.length; i++) {
									//比对历史多边形与现在的多边形,如果存在数组不一样,那么就是拖动的点
									var tmp_o = old_point[i];
									var tmp_n = coordinates[i];
									if (tmp_o[0] != tmp_n[0] || tmp_o[1] != tmp_n[1]) {
										that.select_point_index = tmp_n; //缓存点
										return new ol.geom.MultiPoint([
											tmp_n
										]);
									}
								}
								if (that.select_point_index == null) { //如果没有点
									return null;
								}
								//返回历史点
								return new ol.geom.MultiPoint([
									that.select_point_index
								]);

							}

						}

					}
				})

			];
			return styles;

		},
		res: null, //存储绘画的多边形要素
		cache_point: null, //缓存的历史点
		select_feature: null, //存放的要素
		select_point_index: null, //实时存放选择的变色的点
		delPoint: function() { //删除点,只能删除选定的
			if (this.select != undefined) {
				var a = this.select.getFeatures().getArray();
				var g = a[a.length - 1];
				if (g != undefined) {
					if (g.getGeometry().getCoordinates()[0].length <= 4) {
						// mui.alert('当前不能删除点!');
						return -1;
					}
					if (this.select_point_index == null) {
						// mui.alert('请选择要删除的点!');
						return -1;
					}
					this.cache_point = null;
					this.select_point_index = null;
					this.modify.removePoint();
					return 1;

				} else {
					// mui.alert('当前没有可删除的点!');
				}
			} else {
				// mui.alert('当前没有可删除的点!');
			}

		},
		clickChangePoint: function(point) { //计算点的修改
			var that = this;
			try {
				var fs = that.select.getFeatures().getArray()[0].getGeometry().getCoordinates();
				if (
					that.pointInsideCircle(point, fs) == true) {
					that.select_point_index = fs;
					return;
				}
			} catch (e) {}

		},
		pointInsideCircle: function(point, circle) { //计算鼠标点击点与要素点的距离,判断最近的点,默认在15的分辨率下的20米距离.
			var r;
			if (anorios == 0) { //0代表安卓,1代表ios
				console.log("---------------------当前分辨率参数 是android ");
				r = window.window.map.getView().getZoom() * 0.0002778 * 20 * 130 * 100; //3857坐标要乘110
			} else if (anorios == 1) {
				console.log("------------------当前分辨率参数 是ios ");
				r = window.window.map.getView().getZoom() * 0.0002778 * 20 * 130; //3857坐标要乘110
			} else {
				console.log("---------------当前分辨率参数 是其他 ");
				r = window.window.map.getView().getZoom() * 0.0002778 * 20 * 130 * 100; //3857坐标要乘110
			}

			if (r === 0) return false
			var dx = circle[0] - point[0];
			var dy = circle[1] - point[1];
			return Math.abs(dx) < r && Math.abs(dy) < r
		},
		init: function() { //初始化
			var that = this;
			//初始化一个交互选择控件，并添加到地图容器中
			this.select = new ol.interaction.Select({
				//condition: ol.events.condition.pointerMove,  
				//condition: ol.events.condition.click,
				style: that.m_style(),
				//multi:true
			});

			//选择事件,都是选一个区域
			this.select.on('select', function(evt) {
				if (this.activeFlag == false) {
					return;
				}
				that.clickChangePoint(evt.mapBrowserEvent.coordinate);
				if (evt.selected[0] != 'undefined') {
					that.select.getFeatures().push(that.select_feature)
				}

			});
			$map.addInteraction(this.select);
			var selected_collection = this.select.getFeatures();
			selected_collection.push(this.select_feature);
			that.res = this.select_feature;

			//初始化一个交互编辑控件，并添加到地图容器中
			this.modify = new ol.interaction.Modify({
				features: this.select.getFeatures(),
				style: function(feature) { //将修改控件自带的跟着鼠标移动的蓝点去掉
					return new ol.style.Style({
						image: new ol.style.Circle({
							radius: 10,
							fill: new ol.style.Fill({
								color: [255, 255, 255, 0.01]
							}),
							stroke: new ol.style.Stroke({
								color: [255, 255, 255, 0.01],
								width: 1.5
							})
						}),
						zIndex: 1
					})
				}

			});
			$map.addInteraction(this.modify);
			this.setEvents();

			this.modify.on("modifystart", function(e, b, c) {
				console.info("***开始修改***");
			});
			//***监听多边形修改事件***
			//delPoint方法也会触发该事件
			this.modify.on("modifyend", function(e) {
				var features = e.features.array_;
				var wktformat = new ol.format.WKT();
				if (features != undefined && features[0] != undefined) {
					var _points = features[features.length - 1].getGeometry().getFlatCoordinates();
					var points = [];
					for (var i = 0; i < _points.length / 2; i++) {
						var tmp = [_points[i * 2], _points[i * 2 + 1]];
						points.push(tmp);
					}
					console.log(points);
					that.res = points;
					addFeatures(points); //记录当前多边形点数据
					coordinates = [];
					coordinates = points;
					//计算面积(亩)
					if (ol.sphere.getArea(features[0].getGeometry()) == 0) {
						area = ((Math.abs(ol.sphere.getArea(features[1].getGeometry())) * 0.0015)
							.toFixed(2)).toString();
						console.log("面积", area);
						perimeter = ((Math.abs(ol.sphere.getLength(features[1].getGeometry())))
							.toFixed(2)).toString();
						console.log("周长", perimeter);

					} else {
						area = ((Math.abs(ol.sphere.getArea(features[0].getGeometry())) * 0.0015)
							.toFixed(2)).toString();
						console.log("面积", area);
						perimeter = ((Math.abs(ol.sphere.getLength(features[0].getGeometry())))
							.toFixed(2)).toString();
						console.log("周长", perimeter);
					}
					// 返回监听面积 周长
					typeof onCoordinatesChanged === 'function' && onCoordinatesChanged({
						area: area,
						perimeter: perimeter
					});
				}
				console.info("***修改结束***");
			});

		},
		setEvents: function() {
			var selectedFeatures = this.select.getFeatures(); //选中的要素集
			//添加选中要素变更事件
			this.select.on("change:active", function(e) {
				//遍历选择要素集，返回当前第一个要素（即移除的要素）
				selectedFeatures.forEach(selectedFeatures.remove, selectedFeatures);
			});
		},
		activeFlag: true,
		setActive: function(active) {
			var that = this;
			that.select.setActive(active); //激活选择要素控件
			that.modify.setActive(active); //激活修改要素控件
		},
		clear: function() { //清除结束绘画
			if (this.modify != undefined) {
				this.modify.setActive(false);
				$map.removeInteraction(this.modify);
			}

			if (this.select != undefined) {
				this.select.getFeatures().clear(); //取消选中状态
				this.select.setActive(false);
				$map.removeInteraction(this.select);
			}
			this.res = null;
			this.cache_point = null; //缓存的历史点
			this.select_feature = null; //存放的要素
			this.select_point_index = null; //实时存放选择的变色的点

		},
		getCoordinates: function() { //获取选中的当前多边形的点数据
			return this.select_feature
		}
	};

	//**********图层选择、修改控件***************

	//绘制或修改时，记录每一步操作的多边形边界点数据
	function addFeatures(lats) {
		features.push(lats);
	}
	//回退操作修改多边形图层
	function back(_tmp) {
		Modify.clear();
		var feature = new ol.Feature(
			new ol.geom.Polygon(
				[
					_tmp
				]
			)
		);
		Modify.select_feature = feature; //选中要素
		Modify.init();
		Modify.setActive(true); //开启选择控件、修改控件

		coordinates = _tmp;
		//计算面积(亩)
		area = ((Math.abs(ol.sphere.getArea(feature.getGeometry())) * 0.0015).toFixed(2)).toString();
		console.log("面积：", area);
		perimeter = ((Math.abs(ol.sphere.getLength(feature.getGeometry()))).toFixed(2)).toString();
		console.log("周长：", perimeter);
		// 返回监听面积 周长
		typeof onCoordinatesChanged === 'function' && onCoordinatesChanged({
			area: area,
			perimeter: perimeter
		});
	}

	//判断当前多边形非相邻的线是否相交
	function isXj(bbc) {
		if (bbc.length <= 8) {
			return false;
		}
		for (var i = 0; i < bbc.length / 2; i++) {
			var x1 = bbc[i * 2 + 0];
			var y1 = bbc[i * 2 + 1];
			var x2, y2, x3, y3, x4, y4;
			if (i == bbc.length / 2 - 1) {
				x2 = bbc[0];
				y2 = bbc[1];
			} else {

				x2 = bbc[i * 2 + 2];
				y2 = bbc[i * 2 + 3];
			}

			for (var j = 1; j < bbc.length / 2; j++) {
				if (i == j) {
					continue;
				}
				x3 = bbc[j * 2 + 0];
				y3 = bbc[j * 2 + 1];
				if (j == bbc.length / 2 - 1) {
					x4 = bbc[0];
					y4 = bbc[1];
				} else {

					x4 = bbc[j * 2 + 2];
					y4 = bbc[j * 2 + 3];
				}

				if (x1 == x3 && y1 == y3 && x2 == x4 && y2 == y4) {
					continue;
				}

				var xj = judgeIntersect2(x1, y1, x2, y2, x3, y3, x4, y4);
				if (xj != false) {
					return true;
				}
			}

		}
		return false;

	}

	function judgeIntersect2(x1, y1, x2, y2, x3, y3, x4, y4) {
		//系数 4326的  3857的起码*100
		var xishu = 0.000000000001 * 10000;

		var a = {
			x: x1,
			y: y1
		};
		var b = {
			x: x2,
			y: y2
		};
		var c = {
			x: x3,
			y: y3
		};
		var d = {
			x: x4,
			y: y4
		};

		/** 1 解线性方程组, 求线段交点. **/
		// 如果分母为0 则平行或共线, 不相交  
		var denominator = (b.y - a.y) * (d.x - c.x) - (a.x - b.x) * (c.y - d.y);
		if (denominator == 0) {
			return false;
		}

		// 线段所在直线的交点坐标 (x , y)      
		var x = ((b.x - a.x) * (d.x - c.x) * (c.y - a.y) +
			(b.y - a.y) * (d.x - c.x) * a.x -
			(d.y - c.y) * (b.x - a.x) * c.x) / denominator;
		var y = -((b.y - a.y) * (d.y - c.y) * (c.x - a.x) +
			(b.x - a.x) * (d.y - c.y) * a.y -
			(d.x - c.x) * (b.y - a.y) * c.y) / denominator;

		/** 2 判断交点是否在两条线段上 **/
		if (
			// 交点在线段1上  
			(x - a.x) * (x - b.x) <= 0 && (y - a.y) * (y - b.y) <= 0
			// 且交点也在线段2上  
			&&
			(x - c.x) * (x - d.x) <= 0 && (y - c.y) * (y - d.y) <= 0
		) {

			// 返回交点p  
			var jd = {
				x: x,
				y: y
			}
			//如果焦点为c,d的其中一个,返回false
			if ((Math.abs(jd.x - c.x) <= xishu && Math.abs(jd.y - c.y) <= xishu) ||
				(Math.abs(jd.x - d.x) <= xishu && Math.abs(jd.y - d.y) <= xishu)) {
				return false;
			}

			return jd;
		}
		//否则不相交  
		return false;

	}

	return {
		//绘制多边形初始化
		drawInit: function() {
			Draw.init();
		},
		//选中多边形初始化
		modifyInit: function(lats) {
			var _tmp = [];
			for (var i = 0; i < lats.length; i++) {
				//_tmp.push(ol.proj.transform(lats[i], 'EPSG:4326', 'EPSG:3857'));
				_tmp.push(lats[i]);
			}
			var feature = new ol.Feature(
				new ol.geom.Polygon(
					[
						_tmp
					]
				)
			);
			Modify.select_feature = feature; //选中要素
			Modify.init();
			Modify.setActive(true); //开启选择控件、修改控件
			coordinates = [];
			coordinates = _tmp;
			//计算面积(亩)
			area = ((Math.abs(ol.sphere.getArea(feature.getGeometry())) * 0.0015).toFixed(2)).toString();
			console.log("面积：", area);
			perimeter = ((Math.abs(ol.sphere.getLength(feature.getGeometry()))).toFixed(2)).toString();
			console.log("周长：", perimeter);
			// 返回监听面积 周长
			typeof onCoordinatesChanged === 'function' && onCoordinatesChanged({
				area: area,
				perimeter: perimeter
			});
			//初始化回退操作的数据
			backCursor = 0;
			features = [];
			addFeatures(_tmp); //记录当前多边形点数据
			features_0 = _tmp;
		},
		//删除绘制图层，取消绘制状态
		del: function() {
			Modify.clear();
			features_0 = null;
			Draw.del();
			coordinates = [];
			
			area = 0;
			perimeter = 0;
			// 返回监听面积 周长
			typeof onCoordinatesChanged === 'function' && onCoordinatesChanged({
				area: area,
				perimeter: perimeter
			});
		},
		//删除当前选中的点
		delPoint: function() {
			Modify.delPoint();
		},
		//回退操作,num为1时，代表是绘制图层的回退，不为1时表示为修改图层的回退
		regression: function(num) {
			var backbj = 0;
			backCursor = backCursor + 1;
			if (features != [] && features.length > 0) {
				if (features.length - 1 - backCursor >= 0) {
					back(features[features.length - 1 - backCursor]);
					backbj = 1;
					if (features.length - 1 - backCursor <= 0) {
						backCursor = 0;
						features = []; //回退到0后，清空记录的数据
						addFeatures(features_0); //记录当前多边形点数据
					}
				} else {
					back(features[0]);
					backCursor = 0;
					//回退到最后一个或回退完毕，记录最后一个
					features = []; //回退到0后，清空记录的数据
					addFeatures(features_0); //记录当前多边形点数据
					if (num != 1) {
						// mui.alert('没有可回退的操作!');
					}

				}

			} else {
				backCursor = 0;
				//回退到最后一个或回退完毕，记录最后一个
				features = []; //回退到0后，清空记录的数据
				addFeatures(features_0); //记录当前多边形点数据
			}

			//回退绘制图层时未闭合之前的点
			if (backbj == 0 && backCursor == 0 && operations.length > 0) {
				Modify.clear();
				features_0 = null;
				features = [];
				coordinates = [];
				var operation = operations.pop();
				switch (operation[0]) {
					case "addPoint":
						addPoint.pop();
						drawPolygon();
						break;
					default:
						break;
				}

				//开启绘制状态
				isDraw = true;

			} else if (backbj == 0 && num == 1) {
				Draw.del();
				Draw.init();
				// mui.alert('没有可回退的操作!');
			}
		},
		//获取绘制图层时的第一个点
		getFirstPoint: function() {
			return firstPoint;
		},
		//绘制图层时记录每一步的操作点数据
		addoperation: function(operate, pointNum, coorBefore, coorAfter) {
			operations.push([operate, pointNum, coorBefore, coorAfter]);
		},
		getoperation: function(operate, pointNum, coorBefore, coorAfter) {
			return operations[operations.length - 1];
		},
		getOperations: function() {
			return operations;
		},
		//结束绘制
		finishDrawing: function() {
			if (vector != null) {
				$map.removeLayer(vector);
				vector = null;
			}
			addPoint.push(addPoint[0]);

			var feature = new ol.Feature(
				new ol.geom.Polygon(
					[
						addPoint
					]
				)
			);
			Modify.select_feature = feature; //选中要素
			Modify.init();
			Modify.setActive(true); //开启选择控件、修改控件
			coordinates = addPoint;
			//计算面积(亩)
			area = ((Math.abs(ol.sphere.getArea(feature.getGeometry())) * 0.0015).toFixed(2)).toString();
			console.log("面积：", area);
			perimeter = ((Math.abs(ol.sphere.getLength(feature.getGeometry()))).toFixed(2)).toString();
			console.log("周长：", perimeter);
			// 返回监听面积 周长
			typeof onCoordinatesChanged === 'function' && onCoordinatesChanged({
				area: area,
				perimeter: perimeter
			});
			//初始化回退操作的数据
			backCursor = 0;
			features = [];
			addFeatures(addPoint); //记录当前多边形点数据
			features_0 = addPoint;
			operations.push(["addPoint", addPoint.length - 1, null, addPoint[addPoint.length - 1]]);
		},
		//设置是否正在绘制
		setDrawState: function(isdraw) {
			isDraw = isdraw;
		},
		//返回是否正在绘制
		getDrawState: function() {
			return isDraw;
		},
		getaddPoint: function() {
			return addPoint;
		},
		setaddPoint: function() {
			addPoint = [];
		},
		appendAddPoint: function(coor) {
			addPoint.push(coor);
			drawPolygon();
		},
		setRes: function(lats) {
			coordinates = lats; //3857
		},
		//获取当前绘制图层点数据
		getRes: function() {
			var ps = [];
			for (var tmp in coordinates) {
				var _t = coordinates[tmp];
				//反过来
				var m_center = [_t[0], _t[1]]; //地图中心点-xy坐标
				//经纬度转至经纬度
				m_center = ol.proj.transform(m_center, 'EPSG:3857', 'EPSG:4326');
				ps.push(m_center.join(" "));
			}
			return ps.join(",");

		},
		//获取多边形成型后的点
		getCoordinates: function() {
			return coordinates
		},
		//记录绘制地块时的点
		getPoints: function() {
			return addPoint
		},
		//获取测绘面积(亩)
		getArea: function() {
			return area;
		},
		//获取测绘周长(米)
		getPerimeter: function() {
			return perimeter
		},
		getCoordinatesChanged: function() {
			return onCoordinatesChanged;
		},
		setCoordinatesChanged: function(e) {
			onCoordinatesChanged = e
		},
		//绘制图层时选择的点，判断是否属于当前多边形
		getIstrue: function(point) {
			if (coordinates.length > 0) {
				var feature = new ol.Feature(
					new ol.geom.Polygon(
						[
							coordinates
						]
					)
				);
				var geo = feature.getGeometry(); //feture是几何元素(当前的多边形)
				var isIn = geo.intersectsCoordinate(point);
				return isIn;
			} else {
				return false;
			}
		},
		//判断当前多边形是否自相交
		getisXj: function() {
			if (coordinates != null && coordinates != [] && coordinates.length > 0) {
				var bbc = [];
				for (var i = 0; i < coordinates.length; i++) {
					bbc.push(coordinates[i][0]);
					bbc.push(coordinates[i][1]);
				}
				return isXj(bbc);

			} else {
				return false;
			}

		},
		//获取当前绘制图层的中心点坐标
		getCenterPoint: function() {
			var centerPoint = [];
			var lng = 0.0;
			var lat = 0.0;
			var ps = [];
			for (var tmp in coordinates) {
				var _t = coordinates[tmp];
				//反过来
				var m_center = [_t[0], _t[1]]; //地图中心点-xy坐标
				//经纬度转至经纬度
				m_center = ol.proj.transform(m_center, 'EPSG:3857', 'EPSG:4326');
				ps.push(m_center);
			}
			if (ps.length > 0) {
				for (var tmp in ps) {
					lng = lng + ps[tmp][0];
					lat = lat + ps[tmp][1];
				}
				lng = lng / ps.length;
				lat = lat / ps.length;
				centerPoint.push(lng);
				centerPoint.push(lat);
			}

			return centerPoint;
		}
	}

}
if (typeof module === "object" && typeof module.exports === "object") {
	module.exports = GeometryDraw;
	//export default//建议使用nodejs的module导出方式，如报错请使用export方式导出
}
